<template>
  <div>
    <tableTep
      :tableConfig="state.tableConfig"
      :tableHeader="state.tableHeader"
      :tableHandleList="state.tableHandleList"
      :searchList="state.searchList"
      :searchForm="state.searchForm"
      :getDataAsync="getRoleList"
      @removeHandle="removeHandle"
      @editHandle="editHandle"
      ref="tableTepRef"
    >
      <template v-slot:content>
        <el-col :span="6">
          <el-button type="primary" @click="searchHandle">搜索</el-button>
          <el-button type="primary" @click="resetHandle">重置</el-button>
        </el-col>
      </template>
      <template v-slot:businessHandle>
        <el-button type="primary" @click="addState">新增</el-button>
      </template>
    </tableTep>
    <el-dialog
      v-if="dialogVisible"
      v-model="dialogVisible"
      :title="dialogTitle"
      width="60%"
      @closed="handleClose"
      destroy-on-close
      close-on-press-escape
    >
      <el-form
        label-position="right"
        label-width="100px"
        :model="state.addForm"
        ref="FormTepRef"
      >
        <el-form-item label="名称">
          <el-input v-model="state.addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="state.addForm.remark"></el-input>
        </el-form-item>
        <el-form-item label="权限配置">
          <el-tree
            :data="state.menuList"
            show-checkbox
            node-key="_id"
            default-expand-all
            :props="{ label: 'menuName' }"
            ref="menuTree"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCanCel">取 消</el-button>
          <el-button type="primary" @click="submitHandle">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name:'Role'
}
</script>
<script setup>
import tableTep from "@/components/tableTep/index.vue";
import { reactive, ref, inject, computed, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { clearObj } from "@/utils/utils.js";
const { getRoleList, getMenuList, addRole, editRole, delRole } = inject("$api");
import dayjs from "dayjs";
let tableTepRef = ref(null);
let FormTepRef = ref(null);
let menuTree = ref(null);

const state = reactive({
  tableHeader: [
    {
      prop: "roleName",
      label: "角色名称",
    },
    {
      prop: "remark",
      label: "备注",
    },
    {
      prop: "permissionList",
      label: "权限列表",
      propDefine: (row) => {
        return `<span style="color:red">${1}</span>`;
      },
    },
    {
      label: "更新时间",
      prop: "updateTime",
      propDefine: (row) => {
        return `<span>${dayjs(row.updateTime).format(
          "YYYY-MM-DD HH:mm"
        )}</span>`;
      },
    },
    {
      prop: "createTime",
      label: "创建时间",
      propDefine: (row) => {
        return `<span>${dayjs(row.createTime).format(
          "YYYY-MM-DD HH:mm"
        )}</span>`;
      },
    },
  ],
  tableConfig: {
    showIndex: true, //是否显示序号
    tableHeight: 600, //表格高度
    isSelection: true,
    tableSize: 1,
    isRemember: true,
    defaultOptions: {
      border: true,
    },
    handleOption: {
      handleName: "操作", // 操作列表头名称
      width: 250,
      align: "center",
    },
  },
  tableHandleList: [
    // 具体操作
    {
      label: "编辑",
      handle: "editHandle",
      btnAttr: {
        //按钮配置项
        size: "mini",
        type: "primary",
      },
    },
    // 具体操作
    {
      label: "删除",
      handle: "removeHandle",
      btnAttr: {
        //按钮配置项
        size: "mini",
        type: "danger",
      },
    },
  ],
  searchList: [
    {
      name: "roleName", //字段名
      type: "TextMoudel", //类型
      title: "角色名称",
      required: false, // 必填
      span: 6,
    },
  ],
  searchForm: {
    roleName: "",
  },
  addForm: {
    roleName: "",
    remark: "",
    permissionList: {
      checkedKeys: [],
      halfCheckedKeys: [],
    },
  },
  menuList: [],
});
const dialogVisible = ref(false);
const dialogTitle = ref("");

onMounted(() => {
  getMenu();
});

const getMenu = () => {
  getMenuList().then((res) => {
    let { list } = res;
    state.menuList = [...list];
  });
};

const handleClose = () => {
  dialogVisible.value = false;
  dialogTitle.value = "";
  state.addForm = clearObj(state.addForm);
};

/**
 * @description: 移出操作
 * @param {*}
 * @return {*}
 */
const removeHandle = (row) => {
  ElMessageBox.confirm(`是否删除名称为  ${row.roleName}  的角色?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await delRole({ _id: row._id });
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    await tableTepRef.value.refreshData();
  });
};
/**
 * @description: 修改数据
 * @param {*}
 * @return {*}
 */
const editHandle = (row) => {
  Object.assign(state.addForm, row);
  dialogVisible.value = true;
  dialogTitle.value = "编辑";
  let { checkedKeys } = row.permissionList;
  nextTick(() => {
    menuTree.value.setCheckedKeys(checkedKeys);
  });
};

/**
 * @description: 搜索刷新列表
 * @param {*}
 * @return {*}
 */
const searchHandle = () => {
  tableTepRef.value.refreshData();
};

/**
 * @description:重置搜索
 * @param {*}
 * @return {*}
 */
const resetHandle = () => {
  tableTepRef.value.refreshData();
};

/**
 * @description: 添加操作
 * @param {*}
 * @return {*}
 */
const addState = () => {
  dialogVisible.value = true;
  dialogTitle.value = "新增";
};
/**
 * @description: 取消
 * @param {*}
 * @return {*}
 */
const handleCanCel = () => {
  dialogVisible.value = false;
  dialogTitle.value = "";
  state.addForm = clearObj(state.addForm);
};
/**
 * @description: 提交
 * @param {*}
 * @return {*}
 */
const submitHandle = async () => {
  let res = await FormTepRef.value.validate();
  if (res) {
    let nodes = menuTree.value.getCheckedNodes();
    let halfKeys = menuTree.value.getHalfCheckedKeys();
    let checkedKeys = [];
    let parentKeys = [];
    nodes.map((node) => {
      if (!node.children) {
        checkedKeys.push(node._id);
      } else {
        parentKeys.push(node._id);
      }
    });
    state.addForm.permissionList.checkedKeys = checkedKeys;
    state.addForm.permissionList.halfCheckedKeys = parentKeys.concat(halfKeys);

    if (dialogTitle.value === "新增") {
      addRole(state.addForm).then(() => {
        dialogVisible.value = false;
        dialogTitle.value = "";
        ElMessage({
          message: "创建成功",
          type: "success",
        });
        tableTepRef.value.refreshData();
      });
    }

    if (dialogTitle.value === "编辑") {
      editRole(state.addForm).then(() => {
        dialogVisible.value = false;
        dialogTitle.value = "";
        ElMessage({
          message: "编辑成功",
          type: "success",
        });
        tableTepRef.value.refreshData();
      });
    }
  }
};
</script>
<style scoped>
</style>
